{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "10 - Extract text from documents",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4Pjmz-RORV8E"
      },
      "source": [
        "# Extract text from documents\n",
        "\n",
        "_This notebook is part of a tutorial series on [txtai](https://github.com/neuml/txtai), an AI-powered semantic search platform._\n",
        "\n",
        "Up to this point, all the examples have been working with sections of text, which have already been split through some other means. What happens if we're working with documents? First we need to get the text out of these documents, then figure out how to index to best support similarity search.\n",
        "\n",
        "This notebook shows how documents can have text extracted and segmented to support similarity search."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dk31rbYjSTYm"
      },
      "source": [
        "# Install dependencies\n",
        "\n",
        "Install `txtai` and all dependencies. Since this notebook is using optional pipelines, we need to install the pipeline extras package."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XMQuuun2R06J"
      },
      "source": [
        "%%capture\n",
        "!pip install git+https://github.com/neuml/txtai#egg=txtai[pipeline]\n",
        "\n",
        "# Get test data\n",
        "!wget -N https://github.com/neuml/txtai/releases/download/v3.5.0/tests.tar.gz\n",
        "!tar -xvzf tests.tar.gz\n",
        "\n",
        "# Install NLTK\n",
        "import nltk\n",
        "nltk.download('punkt')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PNPJ95cdTKSS"
      },
      "source": [
        "# Create a Textractor instance\n",
        "\n",
        "The Textractor instance is the main entrypoint for extracting text. This method is backed by Apache Tika, a robust text extraction library written in Java. [Apache Tika](https://tika.apache.org/0.9/formats.html) has support for a large number of file formats: PDF, Word, Excel, HTML and others. The [Python Tika package](https://github.com/chrismattmann/tika-python) automatically installs Tika and starts a local REST API instance used to read extracted data.\n",
        "\n",
        "*Note: This requires Java to be installed locally.*"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nTDwXOUeTH2-"
      },
      "source": [
        "%%capture\n",
        "\n",
        "from txtai.pipeline import Textractor\n",
        "\n",
        "# Create textractor model\n",
        "textractor = Textractor()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-vGR_piwZZO6"
      },
      "source": [
        "# Extract text\n",
        "\n",
        "The example below shows how to extract text from a file."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 106
        },
        "id": "-K2YJJzsVtfq",
        "outputId": "a18f5b12-f90c-4d8d-e0b7-64350d76a086"
      },
      "source": [
        "textractor(\"txtai/article.pdf\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'Introducing txtai, an AI-powered search engine built on Transformers Add Natural Language Understanding to any application Search is the base of many applications. Once data starts to pile up, users want to be able to find it. It’s the foundation of the internet and an ever-growing challenge that is never solved or done. The field of Natural Language Processing (NLP) is rapidly evolving with a number of new developments. Large-scale general language models are an exciting new capability allowing us to add amazing functionality quickly with limited compute and people. Innovation continues with new models and advancements coming in at what seems a weekly basis. This article introduces txtai, an AI-powered search engine that enables Natural Language Understanding (NLU) based search in any application. Introducing txtai txtai builds an AI-powered index over sections of text. txtai supports building text indices to perform similarity searches and create extractive question-answering based systems. txtai also has functionality for zero-shot classification. txtai is open source and available on GitHub. txtai and/or the concepts behind it has already been used to power the Natural Language Processing (NLP) applications listed below: • paperai — AI-powered literature discovery and review engine for medical/scientific papers • tldrstory — AI-powered understanding of headlines and story text • neuspo — Fact-driven, real-time sports event and news site • codequestion — Ask coding questions directly from the terminal Build an Embeddings index For small lists of texts, the method above works. But for larger repositories of documents, it doesn’t make sense to tokenize and convert all embeddings for each query. txtai supports building pre- computed indices which significantly improves performance. Building on the previous example, the following example runs an index method to build and store the text embeddings. In this case, only the query is converted to an embeddings vector each search. https://github.com/neuml/codequestion https://neuspo.com/ https://github.com/neuml/tldrstory https://github.com/neuml/paperai Introducing txtai, an AI-powered search engine built on Transformers Add Natural Language Understanding to any application Introducing txtai Build an Embeddings index'"
            ]
          },
          "metadata": {},
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "n2jndgE-JyWX"
      },
      "source": [
        "Note that the text from the article was extracted into a single string. Depending on the articles, this may be acceptable. For long articles, often you'll want to split the content into logical sections to build better downstream vectors."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1w2bhBCPOUdu"
      },
      "source": [
        "# Extract sentences"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "PKZVK5vuOTqB",
        "outputId": "cb8d688e-9d55-41a2-de26-a86d4e54b23d"
      },
      "source": [
        "textractor = Textractor(sentences=True)\n",
        "textractor(\"txtai/article.pdf\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['Introducing txtai, an AI-powered search engine built on Transformers Add Natural Language Understanding to any application Search is the base of many applications.',\n",
              " 'Once data starts to pile up, users want to be able to find it.',\n",
              " 'It’s the foundation of the internet and an ever-growing challenge that is never solved or done.',\n",
              " 'The field of Natural Language Processing (NLP) is rapidly evolving with a number of new developments.',\n",
              " 'Large-scale general language models are an exciting new capability allowing us to add amazing functionality quickly with limited compute and people.',\n",
              " 'Innovation continues with new models and advancements coming in at what seems a weekly basis.',\n",
              " 'This article introduces txtai, an AI-powered search engine that enables Natural Language Understanding (NLU) based search in any application.',\n",
              " 'Introducing txtai txtai builds an AI-powered index over sections of text.',\n",
              " 'txtai supports building text indices to perform similarity searches and create extractive question-answering based systems.',\n",
              " 'txtai also has functionality for zero-shot classification.',\n",
              " 'txtai is open source and available on GitHub.',\n",
              " 'txtai and/or the concepts behind it has already been used to power the Natural Language Processing (NLP) applications listed below: • paperai — AI-powered literature discovery and review engine for medical/scientific papers • tldrstory — AI-powered understanding of headlines and story text • neuspo — Fact-driven, real-time sports event and news site • codequestion — Ask coding questions directly from the terminal Build an Embeddings index For small lists of texts, the method above works.',\n",
              " 'But for larger repositories of documents, it doesn’t make sense to tokenize and convert all embeddings for each query.',\n",
              " 'txtai supports building pre- computed indices which significantly improves performance.',\n",
              " 'Building on the previous example, the following example runs an index method to build and store the text embeddings.',\n",
              " 'In this case, only the query is converted to an embeddings vector each search.',\n",
              " 'https://github.com/neuml/codequestion https://neuspo.com/ https://github.com/neuml/tldrstory https://github.com/neuml/paperai Introducing txtai, an AI-powered search engine built on Transformers Add Natural Language Understanding to any application Introducing txtai Build an Embeddings index']"
            ]
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vdVCCc9UOv5S"
      },
      "source": [
        "Now the document is split up at the sentence level. These sentences can be feed to a workflow that adds each sentence to an embeddings index. Depending on the task, this may work well. Alternatively, it may be even better to split at the paragraph level."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z1H8XYkaSoP4"
      },
      "source": [
        "# Extract paragraphs"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "9VUito4ISoAe",
        "outputId": "21770771-faa4-4340-a1ab-7fb0a8177f4c"
      },
      "source": [
        "textractor = Textractor(paragraphs=True)\n",
        "textractor(\"txtai/article.pdf\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['Introducing txtai, an AI-powered search engine built on Transformers',\n",
              " 'Add Natural Language Understanding to any application',\n",
              " 'Search is the base of many applications. Once data starts to pile up, users want to be able to find it. It’s the foundation of the internet and an ever-growing challenge that is never solved or done.',\n",
              " 'The field of Natural Language Processing (NLP) is rapidly evolving with a number of new developments. Large-scale general language models are an exciting new capability allowing us to add amazing functionality quickly with limited compute and people. Innovation continues with new models and advancements coming in at what seems a weekly basis.',\n",
              " 'This article introduces txtai, an AI-powered search engine that enables Natural Language Understanding (NLU) based search in any application.',\n",
              " 'Introducing txtai txtai builds an AI-powered index over sections of text. txtai supports building text indices to perform similarity searches and create extractive question-answering based systems. txtai also has functionality for zero-shot classification. txtai is open source and available on GitHub.',\n",
              " 'txtai and/or the concepts behind it has already been used to power the Natural Language Processing (NLP) applications listed below:',\n",
              " '• paperai — AI-powered literature discovery and review engine for medical/scientific papers • tldrstory — AI-powered understanding of headlines and story text • neuspo — Fact-driven, real-time sports event and news site • codequestion — Ask coding questions directly from the terminal',\n",
              " 'Build an Embeddings index For small lists of texts, the method above works. But for larger repositories of documents, it doesn’t make sense to tokenize and convert all embeddings for each query. txtai supports building pre- computed indices which significantly improves performance.',\n",
              " 'Building on the previous example, the following example runs an index method to build and store the text embeddings. In this case, only the query is converted to an embeddings vector each search.',\n",
              " 'https://github.com/neuml/codequestion https://neuspo.com/ https://github.com/neuml/tldrstory https://github.com/neuml/paperai',\n",
              " 'Introducing txtai, an AI-powered search engine built on Transformers Add Natural Language Understanding to any application',\n",
              " 'Introducing txtai Build an Embeddings index']"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ]
    }
  ]
}